
package refund;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import common.StringUtil;

/**
 * Created by lichunlin on 2018/5/29.
 */

public class RefundService {

	private long userId;// 用户的id
	private long balance;// 余额
	public static final String IP = "https://wonapi.maxleap.cn/1.0";

	public RefundService(long userId, long balance) {
		super();
		this.userId = userId;
		this.balance = balance;
	}

	private static final OkHttpClient mOkHttpClient = new OkHttpClient();
	private Gson gson = new Gson();

	static {
		mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
		mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
		mOkHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
	}

	public void loginServer(ReFundFinish reFundFinish) {
		ModelUploadLogin modelUploadLogin = new ModelUploadLogin();
//		modelUploadLogin.setPhone("18217689196");
		modelUploadLogin.setPhone("13862584349");
		modelUploadLogin.setPassword("11111111");

		String json = gson.toJson(modelUploadLogin);
		String url = IP + "/users/login";

		MediaType mediaType = MediaType.parse("application/json");
		RequestBody body = RequestBody.create(mediaType, json);

		final Request request = new Request.Builder().url(url).post(body).addHeader("content-type", "application/json")
				.build();

		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
			}

			@Override
			public void onResponse(Response response) throws IOException {
				if (null != response && response.isSuccessful()) {
					try {
						String htmlStr = response.body().string();
						if (!StringUtil.isEmpty(htmlStr)) {
							ModelLogin loginResult = gson.fromJson(htmlStr, new TypeToken<ModelLogin>() {
							}.getType());
							if (null != loginResult) {
								postRefundServer(loginResult,reFundFinish);
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	// 修改余额的接口
	protected void postRefundServer(ModelLogin loginResult,ReFundFinish reFundFinish) {
		RefundRequest refundRequest = new RefundRequest();
		refundRequest.setBalance(balance);
		String json = gson.toJson(refundRequest);

		String url = "http://api.maxapps.cn/1.0/mems/updateMemBalance/" + userId;
		MediaType mediaType = MediaType.parse("application/json");
		RequestBody body = RequestBody.create(mediaType, json);

		final Request request = new Request.Builder().url(url).post(body).addHeader("content-type", "application/json")
				.addHeader("X-ml-APIKey", loginResult.getApiKey()).addHeader("X-ml-appid", loginResult.getAppId())
				.addHeader("x-ml-session-token", loginResult.getSessionToken())
				.addHeader("x-ml-masterkey", "RXlCeTRXRXE1Qk1YdUZERG9QMkVNZw").build();

		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {

			}

			@Override
			public void onResponse(Response response) throws IOException {
				if (null != response && response.isSuccessful()) {
					try {
						String htmlStr = response.body().string();
						if (!StringUtil.isEmpty(htmlStr)) {
							reFundFinish.reFundFinish();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	/**
	 * 2015-09-09 LCL
	 *
	 * 网络请求中汉字要进行UTF-8
	 * 
	 * @return 根据字符串的编码格式转换为UTF－8
	 */
	public String urlEncode(String msg) {
		try {
			String result = URLEncoder.encode(msg, "UTF-8");
			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	final static String PLEASE_SELECT = "请选择...";

	public static boolean isEmpty(Object o) {
		return o == null || "".equals(o.toString().trim()) || "null".equalsIgnoreCase(o.toString().trim())
				|| "undefined".equalsIgnoreCase(o.toString().trim()) || PLEASE_SELECT.equals(o.toString().trim())
				|| "\"\"".equals(o.toString().trim());
	}

	public static void main(String[] args) {
		// VouchersService vouchersService = new
		// VouchersService("5abdfb11b14a3d00051b93c4", 43);
//		RefundService vouchersService = new RefundService("5aaf23cfad16f000085fab3c", "5");
//		vouchersService.loginServer();
	}

	// 获取订单的已完成的
	// public void getMallVoucherServer(ModelLogin loginResult) {
	// ModelVouchersUpload modelOrderStatusUpload = new ModelVouchersUpload();
	// modelOrderStatusUpload.setName("维修奖励");
	//
	// String json = urlEncode(gson.toJson(modelOrderStatusUpload));
	// String url = IP.IP + "/mallVoucher?order=-updatedAt&skip=0&where=" + json;
	// final Request request = new Request.Builder()
	// .url(url)
	// .addHeader("cache-control", "no-cache")
	// .addHeader("content-type", "application/json")
	// .addHeader("accept", "application/json")
	// .addHeader("X-ml-APIKey", loginResult.getApiKey())
	// .addHeader("X-ml-appid", loginResult.getAppId())
	// .addHeader("x-ml-mallid", mallId)
	// .addHeader("x-ml-session-token", loginResult.getSessionToken())
	// .build();
	// Call call = mOkHttpClient.newCall(request);
	// //请求加入调度
	// call.enqueue(new Callback() {
	// @Override
	// public void onFailure(Request request, IOException e) {
	// }
	//
	// @Override
	// public void onResponse(final Response response) throws IOException {
	// if (null != response && response.isSuccessful()) {
	// try {
	// String htmlStr = response.body().string();
	// if (!StringUtil.isEmpty(htmlStr)) {
	// ModelVouchersResponse modelVouchersResponse = gson.fromJson(htmlStr, new
	// TypeToken<ModelVouchersResponse>() {
	// }.getType());
	// if (null != modelVouchersResponse) {
	// List<ModelVouchers> modelVouchers = modelVouchersResponse.getResults();
	// if(null != modelVouchers && modelVouchers.size() > 0) {
	// postMallVoucherServer(modelVouchers.get(0));
	// }
	// }
	// }
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// }
	// });
	// }

}
